package com.example.security.controller;

import com.example.security.common.ResultInfo;
import com.example.security.entity.UserEntity;
import com.example.security.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author novel
 * @date 2020/11/4
 */
@RequestMapping("/user")
@RestController
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ModelAndView list(ModelAndView modelAndView) {
        List<UserEntity> list = userService.list();
        modelAndView.addObject("list", list);
        modelAndView.setViewName("list");
        return modelAndView;
    }

    @GetMapping("/{id}")
    public ResultInfo get(@PathVariable Integer id) {
        UserEntity user = userService.getUserById(id);
        return ResultInfo.success("success", user);
    }

    @PreAuthorize("hasAnyRole('USER')")
    @PostMapping
    public ResultInfo add(UserEntity userEntity) {
        Boolean result = userService.add(userEntity);
        return result ? ResultInfo.success("success", userEntity) : ResultInfo.error(500, "error");
    }

    @PreAuthorize("hasAnyRole('ADMIN')")
    @GetMapping("/delete/{id}")
    public ResultInfo deleteUser(@PathVariable Integer id) {
        Boolean result = userService.deleteUserById(id);
        return result ? ResultInfo.success("success", null) : ResultInfo.error(500, "error");
    }


    @RequestMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String printAdmin() {
        return "如果你看见这句话，说明你有ADMIN角色";
    }

    @RequestMapping("/user")
    @PreAuthorize("hasRole('USER')")
    public String printUser() {
        return "如果你看见这句话，说明你有USER角色";
    }
}
